package com.seecoder.BlueWhale.schedule;


import com.seecoder.BlueWhale.enums.OrderStatusEnum;
import com.seecoder.BlueWhale.po.Order;
import com.seecoder.BlueWhale.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.transaction.Transactional;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class OrderScheduler {

    @Autowired
    private OrderRepository orderRepository;

    //@Scheduled(fixedRate = 86400000) // 每天执行一次，单位是毫秒
    @Scheduled(fixedRate = 10000)
    @Transactional
    public void endUnpaidOrders() {
        Calendar calendar = Calendar.getInstance();
        //calendar.add(Calendar.DAY_OF_YEAR, 0);
        calendar.add(Calendar.MINUTE, 0);
        Date fourteenDaysAgo = calendar.getTime();

        List<Order> unpaidOrders = orderRepository.findUnpaidOrdersBefore(fourteenDaysAgo);

        for (Order order : unpaidOrders) {
            order.setStatus(OrderStatusEnum.CANCEL);
            orderRepository.save(order);
        }
    }
}
